#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>

#define LINE_NUM 1024
#define OPT_NUM 64

char line_command[LINE_NUM];//命令行
char* myargv[OPT_NUM];//选项

int main()
{
    while(1){
        //模拟界面
        printf("用户名@主机名 # "); 
        fflush(stdout);

        //命令行
        char * r = fgets(line_command, sizeof(line_command), stdin);
        assert(r != NULL);
        line_command[strlen(line_command)-1] = 0;
        int i = 1;
        myargv[0] = strtok(line_command, " ");

        //为ls上色
        if(myargv[0] && !strcmp(myargv[0], "ls"))
        {
            myargv[i++] = "--color=auto";
        }

        //拆分命令
        while(myargv[i++] = strtok(NULL, " "));

        //将父进程chdir
        if(myargv[0] && myargv [1] && !strcmp(myargv[0],"cd"))
        {
            chdir(myargv[1]);
            continue;
        }

#if DEBUG 
        //printf(line_command);
       for(int j = 0; myargv[j] != NULL; j++)
       {
           printf("%d: %s\n", j, myargv[j]);
       }
#endif
       //子进程执行进程替换，执行系统指令
       pid_t id = fork();
       //assert(id != 0);
       if(!id)
       {
           //child
           execvp(myargv[0],myargv);
       }
       int status = 0;
       waitpid(id, &status, 0); 
    }
}
